package com.itboye.lottery.dialog;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.bylibrary.util.ScreenUtil;
import com.itboye.lottery.R;
import com.itboye.lottery.alert.ByAlert;
import com.itboye.lottery.base.BaseDialog;
import com.itboye.lottery.bean.BascketballBean;
import com.itboye.lottery.bean.FootballMatchBean;
import com.itboye.lottery.enums.LotteryType;
import com.itboye.lottery.listeners.SelectLisenter;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.itboye.lottery.utils.BetSelectMatches.bascketballMap;

public class JclqHHDialog extends BaseDialog implements CompoundButton.OnCheckedChangeListener {
    private LotteryType lotteryType;
    private int gPosition;
    private int cPosition;
    Context mContext;
    @BindView(R.id.ll_spf)
    RelativeLayout ll_spf;
    @BindView(R.id.ll_rqspf)
    RelativeLayout ll_rqspf;
    @BindView(R.id.ll_zjq)
    RelativeLayout llZjq;
    private SelectLisenter selectListener;

    @BindView(R.id.llSPFContainer)
    LinearLayout llSPFContainer;
    @BindView(R.id.llZJQContainer)
    LinearLayout llZJQContainer;
    @BindView(R.id.llSFCContainer)
    LinearLayout llSFCContainer;
    @BindView(R.id.homeTeamName)
    TextView homeTeamName;
    @BindView(R.id.awayTeamName)
    TextView awayTeamName;
    @BindView(R.id.tv_spf_txt)
    TextView tv_spf_txt;
    @BindView(R.id.tv_rspf_txt)
    TextView tv_rspf_txt;
    @BindView(R.id.ll_sfc_kesheng)
    RelativeLayout ll_sfc_kesheng;
    @BindView(R.id.ll_sfc_zhusheng)
    RelativeLayout ll_sfc_zhusheng;

    public JclqHHDialog(Context context, ArrayList<FootballMatchBean> footballMatchBeanArrayList, int matchPostion, int cPosition, HashMap<String, Map<String, String>> map, LotteryType lotteryType) {
        super(context);
        this.lotteryType = lotteryType;
        this.gPosition = matchPostion;
        this.cPosition = cPosition;
        this.mContext = context;
        this.footballMatchBeanArrayList = footballMatchBeanArrayList;
        initView();
    }

    public void setSelectListener(SelectLisenter selectListener) {
        this.selectListener = selectListener;
    }

    //red_white_selecter 的边线宽度
    int splitWidth = 0;

    private void initView() {
        setContentView(R.layout.dialog_jclq_hh);
        resetAllViews();
        initTeam();
        splitWidth = ScreenUtil.dpToPx(mContext, 0.5f);
        int height = ScreenUtil.dpToPx(mContext, 54);
        int width = ScreenUtil.getScreenWidth(mContext) - ScreenUtil.dip2px(mContext, 40);
        System.out.println("屏幕寬度：：" + ScreenUtil.getScreenWidth(mContext) + ">>>>>>>." + width);
        int vWidth = 0;
        if (lotteryType == LotteryType.SHOWALL) {
            initShowAllView();
            vWidth = width / 2;
            addSPF(vWidth, height, 2, "0_frf_", ll_spf, 0, footballMatchBeanArrayList.get(gPosition).getBascketballBeanArrayList().get(cPosition).getMNL());//非让分
            addSPF(vWidth, height, 2, "1_rf_", ll_rqspf, 1, footballMatchBeanArrayList.get(gPosition).getBascketballBeanArrayList().get(cPosition).getHDC());//让分
            vWidth = width / 3;
            addDXF(vWidth, height, 3);//大小分
            vWidth = width / 6;
            addSFC(vWidth, height, 6);//胜负差
        }
        //比分
        vWidth = width / 5;
//        addBF(vWidth, height, 5);

    }

    private void initTeam() {
        awayTeamName.setText(footballMatchBeanArrayList.get(gPosition).getBascketballBeanArrayList().get(cPosition).getH_cn_abbr());
        homeTeamName.setText(footballMatchBeanArrayList.get(gPosition).getBascketballBeanArrayList().get(cPosition).getA_cn_abbr());
    }


    private void initShowAllView() {
        llSPFContainer.setVisibility(View.VISIBLE);
        llZJQContainer.setVisibility(View.VISIBLE);
        llSFCContainer.setVisibility(View.VISIBLE);
    }

    private void resetAllViews() {
        llSPFContainer.setVisibility(View.GONE);
        llZJQContainer.setVisibility(View.GONE);
        llSFCContainer.setVisibility(View.GONE);
    }

    public JclqHHDialog(Context context, boolean fromButton) {
        super(context, fromButton);
    }

    private ArrayList<FootballMatchBean> footballMatchBeanArrayList;


    @OnClick(R.id.tv_cancel)
    void close() {
        dismiss();
    }

    @OnClick(R.id.tv_sure)
    void sure() {
//        Map<String, Map<String, String>> map = new LinkedHashMap<>();
        clearAndBuildData();
        if (this.selectListener != null) {
            this.selectListener.onSelect(footballMatchBeanArrayList, bascketballMap);
        }
        dismiss();
    }

    private void clearAndBuildData() {
        Map<String, String> spfCd = getCheckData(ll_spf);
        if (spfCd.size() > 0) {
            bascketballMap.put(gPosition + "_" + cPosition + "_" + "0", spfCd);
        } else {
            bascketballMap.remove(gPosition + "_" + cPosition + "_" + "0");
        }
        Map<String, String> rspfCd = getCheckData(ll_rqspf);
        if (rspfCd.size() > 0) {
            bascketballMap.put(gPosition + "_" + cPosition + "_" + "1", rspfCd);
        } else {
            bascketballMap.remove(gPosition + "_" + cPosition + "_" + "1");
        }
        Map<String, String> zjqCd = getCheckData(llZjq);
        if (zjqCd.size() > 0) {
            bascketballMap.put(gPosition + "_" + cPosition + "_" + "2", zjqCd);
        } else {
            bascketballMap.remove(gPosition + "_" + cPosition + "_" + "2");
        }
        Map<String, String> sfc_zhusheng = getCheckData(ll_sfc_zhusheng);
        if (sfc_zhusheng.size() > 0) {
            bascketballMap.put(gPosition + "_" + cPosition + "_" + "3", sfc_zhusheng);
        } else {
            bascketballMap.remove(gPosition + "_" + cPosition + "_" + "3");
        }
        Map<String, String> sfc_kesheng = getCheckData(ll_sfc_kesheng);
        if (sfc_kesheng.size() > 0) {
            bascketballMap.put(gPosition + "_" + cPosition + "_" + "4", sfc_kesheng);
        } else {
            bascketballMap.remove(gPosition + "_" + cPosition + "_" + "4");
        }
    }

    private Map<String, String> getCheckData(ViewGroup viewGroup) {
        Map<String, String> list = new HashMap<>();
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            CheckBox checkBox = (CheckBox) viewGroup.getChildAt(i);
            if (checkBox.isChecked()) {
                list.put(checkBox.getTag().toString(), checkBox.getTag().toString());
            }
        }

        return list;
    }

    //胜平负 让球胜平负
    void addSPF(int width, int height, int maxLine, String perfix, ViewGroup view, int dataIndex, BascketballBean.MNLEntity hadBean) {
        int wm = 0;
        int hm = -splitWidth;
        //因为我从0的时候就+height 所有初始化的时候-height 就刚刚好是0
        int topMargin = -height;
        int leftMargin = ((maxLine - 1) * splitWidth) / 2;
        int index = 0;
        for (int i = 0; i < 2; i++) {
            leftMargin += width;
            wm += ScreenUtil.dpToPx(mContext, 0.5f);
            if (index % maxLine == 0) {
                wm = 0;
                //这里初始化 ((maxLine - 1) * splitWidth) / 2 是由于两个格子都有边框 所有并排在一起的地方会很粗
                //我就将后一个的位置的边线与前一个重叠 然后重叠出来的空间 分配给整个容器左右两边当间距
                leftMargin = ((maxLine - 1) * splitWidth) / 2;
                topMargin += height;
                hm += splitWidth;
            }
            StringBuilder str = new StringBuilder();
            boolean isCheck = false;
            boolean isNotSale = false;
            String tagStr = "";
            if (hadBean == null) {
                str.append("未开售");
                isNotSale = true;
            } else {
                switch (i) {
                    case 1://主胜
                        isNotSale = hadBean.getH().isEmpty();
                        tagStr = "主胜_" + hadBean.getH();
                        str.append("主胜" + hadBean.getH());
                        break;
                    case 0://平
                        str.append("客胜" + hadBean.getA());
                        isNotSale = hadBean.getA().isEmpty();
                        tagStr = ("客胜_" + hadBean.getA());
                        break;
                }
            }
            StringBuilder tag = new StringBuilder();
            tag.append(perfix + i + "_" + tagStr + "_" + (hadBean == null ? "0" : hadBean.getSingle()));
            Log.v("checkBox", "tag dialog" + tag.toString());
            isCheck = isCheckThisView(tag.toString(), gPosition + "_" + cPosition + "_" + String.valueOf(dataIndex));
            if (isNotSale) {//isSale为true
                isCheck = false;
            }
            view.addView(createCheckBox(width, height,
                    leftMargin > 0 ? leftMargin - wm : leftMargin,
                    topMargin > 0 ? topMargin - hm : topMargin,
                    str.toString(), tag.toString(), isCheck, 0, "", !isNotSale));
            index++;
        }
        if (dataIndex==1) {
            if (Double.parseDouble(hadBean.getFixedodds())<0) {
                tv_spf_txt.setText(Html.fromHtml("<font color='blue'>让分<br />"+hadBean.getFixedodds()+"</font>"));
            }else{
                tv_spf_txt.setText(Html.fromHtml("<font color='white'>让分<br />"+hadBean.getFixedodds()+"</font>"));
            }
        }
    }

    //大小分
    void addDXF(int width, int height, int maxLine) {
        int wm = 0;
        int hm = -splitWidth;
        //因为我从0的时候就+height 所有初始化的时候-height 就刚刚好是0
        int topMargin = -height;
        int leftMargin = ((maxLine - 1) * splitWidth) / 2;
        int index = 0;
        BascketballBean.HILOEntity hilo = footballMatchBeanArrayList.get(gPosition).getBascketballBeanArrayList().get(cPosition).getHILO();
        for (int i = 0; i < 3; i++) {
            leftMargin += width;
            wm += ScreenUtil.dpToPx(mContext, 0.5f);
            if (index % maxLine == 0) {
                wm = 0;
                //这里初始化 ((maxLine - 1) * splitWidth) / 2 是由于两个格子都有边框 所有并排在一起的地方会很粗
                //我就将后一个的位置的边线与前一个重叠 然后重叠出来的空间 分配给整个容器左右两边当间距
                leftMargin = ((maxLine - 1) * splitWidth) / 2;
                topMargin += height;
                hm += splitWidth;
            }
            StringBuilder str = new StringBuilder();
            String peilv = "0";
            boolean isChecked = false;
            boolean isNotSale = false;
            String daxiaofen = " ";
            if (hilo == null) {
                isNotSale = false;
                str.append("未开售");
            } else {
                isNotSale = true;
                switch (i) {
                    case 0:
                        daxiaofen = "大分";
                        peilv = hilo.getH();
                        str.append(daxiaofen + "" + peilv);
                        break;
                    case 1:
                        daxiaofen = " ";
                        peilv = hilo.getFixedodds();
                        str.append(peilv);
                        isNotSale = false;
                        break;
                    case 2:
                        daxiaofen = "小分";
                        peilv = hilo.getL();
                        str.append(daxiaofen + "" + peilv);
                        break;
                }
//                str.append("<br/><small><small>");
            }
            str.append("</small></small>");
            StringBuilder tag = new StringBuilder();
            tag.append("2_dxf_" + i + "_" + daxiaofen + "_" + peilv + "_" + (hilo == null ? "0" : hilo.getSingle()));
            isChecked = isCheckThisView(tag.toString(), gPosition + "_" + cPosition + "_" + "2");
            llZjq.addView(createCheckBox(width, height, leftMargin > 0 ? leftMargin - wm : leftMargin,
                    topMargin > 0 ? topMargin - hm : topMargin,
                    str.toString(), tag.toString(), isChecked, isNotSale));
            index++;
        }
    }

    /**
     * 解析tag参数
     *
     * @param tag
     * @return
     */
    boolean isCheckThisView(String tag, String index) {
        if (bascketballMap.get(index) != null) {
            return bascketballMap.get(index).get(tag) != null;
        }
        return false;
    }

    //胜负差
    void addSFC(int width, int height, int maxLine) {
        int wm = 0;
        int hm = -splitWidth;
        //因为我从0的时候就+height 所有初始化的时候-height 就刚刚好是0
        int topMargin = -height;
        int leftMargin = ((maxLine - 1) * splitWidth) / 2;
        int index = 0;
        BascketballBean.WNMEntity hafuBean = footballMatchBeanArrayList.get(gPosition).getBascketballBeanArrayList().get(cPosition).getWNM();
        String[] sfcArray = mContext.getResources().getStringArray(R.array.jclq_sfc);
        if (hafuBean != null) {
            String keys[] = getFiledName(hafuBean.getSpecial_odds());//change是AS中instant run工具生成出来的，关于instant run的介绍https://segmentfault.com/a/1190000004039742。而serialVersionUID则是序列化验证版本一致性的。//所以使用AS开发中使用发射时最好做一下判断
            for (int i = 0; i < (12); i++) {
                String key = keys[i];
                Object[] values = getFieldValueByName(key, hafuBean.getSpecial_odds());
                leftMargin += width;
                wm += ScreenUtil.dpToPx(mContext, 0.5f);
                if (index % maxLine == 0) {
                    wm = 0;
                    //这里初始化 ((maxLine - 1) * splitWidth) / 2 是由于两个格子都有边框 所有并排在一起的地方会很粗
                    //我就将后一个的位置的边线与前一个重叠 然后重叠出来的空间 分配给整个容器左右两边当间距
                    leftMargin = ((maxLine - 1) * splitWidth) / 2;
                    topMargin += height;
                    hm += splitWidth;
                }
                StringBuilder str = new StringBuilder();
                int position = i <= 5 ? i : Math.abs(i - 6);
                int line = i <= 5 ? 4 : 3;
                str.append(sfcArray[position]);
                StringBuilder tag = new StringBuilder();
                String value = i <= 5 ? values[1] + "" : values[0] + "";
                tag.append(line + "_sfc_" + i + "_" + str.toString()  + "_" +value + "_" + (hafuBean == null ? "0" : hafuBean.getSingle()));
                str.append("<br/><small><small>");
                str.append(value);
                str.append("</small></small>");
                boolean isCheck = isCheckThisView(tag.toString(), gPosition + "_" + cPosition + "_" + line);
                if (i <= 5) {
                    ll_sfc_kesheng.addView(createCheckBox(width, height, leftMargin > 0 ? leftMargin - wm : leftMargin,
                            topMargin > 0 ? topMargin - hm : topMargin,
                            str.toString(), tag.toString(), isCheck));
                } else {
                    if (i == 6) {
                        topMargin = 0;
                    }
                    ll_sfc_zhusheng.addView(createCheckBox(width, height, leftMargin > 0 ? leftMargin - wm : leftMargin,
                            topMargin > 0 ? topMargin - hm : topMargin,
                            str.toString(), tag.toString(), isCheck));
                }
                index++;
            }
        }
    }

    //插入冒号
    private String addColon(String number) {
        if (number == null) {
            return "";
        }
        try {
            int str1 = Integer.parseInt(number.substring(0, 2));
            int str2 = Integer.parseInt(number.substring(2, 4));
            return str1 + ":" + str2;
        } catch (Exception e) {
            return number;
        }
    }

    /**
     * 获取属性名数组
     */
    private static String[] getFiledName(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
//            System.out.println(fields[i].getType());
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }

    /* 根据属性名获取属性值
     * */
    private static Object[] getFieldValueByName(String fieldName, Object o) {
        String firstLetter = "";
        Object value[] = new Object[2];
        try {
            firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object values = method.invoke(o, new Object[]{});
            if (firstLetter.startsWith("w") || firstLetter.startsWith("W")) {
                value[0] = values;
            } else {
                value[1] = values;
            }
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            value[0] = "0";
            value[1] = "0";
            return value;
        }
    }

    CheckBox createCheckBox(int width, int height, int leftMargin, int topMargin, String text, String tag, boolean isCheck) {
        return createCheckBox(width, height, leftMargin, topMargin, text, tag, isCheck, -1, "", true);
    }

    CheckBox createCheckBox(int width, int height, int leftMargin, int topMargin, String text, String tag, boolean isCheck, boolean isNotSale) {
        return createCheckBox(width, height, leftMargin, topMargin, text, tag, isCheck, -1, "", isNotSale);
    }

    CheckBox createCheckBox(int width, int height, int leftMargin, int topMargin, String text, String tag, boolean isCheck, int color, String keyword, boolean isNotSale) {
        CheckBox cb = new CheckBox(mContext);
        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(width, height);
        rl.leftMargin = leftMargin;
        rl.topMargin = topMargin;
        cb.setLayoutParams(rl);
        cb.setButtonDrawable(R.color.bh);
        cb.setTextColor(ContextCompat.getColorStateList(mContext, R.color.black_white_selector));
        cb.setGravity(Gravity.CENTER);
        cb.setBackgroundResource(R.drawable.red_white_selecter);
        cb.setTag(tag);
        cb.setText(Html.fromHtml(text));
//        cb.setText(StringUtils.matcherSearchText(color, text, keyword));
        cb.setChecked(isCheck);
        cb.setEnabled(isNotSale);
//        cb.setOnCheckedChangeListener(this);
/*       if(type.equals(JCZQSHOWTYPE.SHOWDG) && (tag.contains("rqspf") || tag.contains("spf"))) {
            cb.setText("未开售");
            cb.setEnabled(false);
            cb.setTextColor(ContextCompat.getColor(getContext(),R.color.b));
        }*/
//       if(type.equals(JCZQSHOWTYPE.SHOWDG) && (tag.contains("rqspf"))) {
//           //让胜平负是不支持单关的；所以这里我们是需要将其弄成未开售
//            cb.setText("未开售");
//            cb.setEnabled(false);
//            cb.setTextColor(ContextCompat.getColor(getContext(),R.color.b));
//        }
        return cb;
    }

    private boolean isSelectCurrentMatch(String key) {
        boolean hasSelect = false;
        Iterator<String> keySet = bascketballMap.keySet().iterator();
        while (keySet.hasNext()) {
            String mapKey = keySet.next();
            String str1 = mapKey.split("_")[0];
            String str2 = mapKey.split("_")[1];
            String str3 = mapKey.split("_")[2];
            if (str1.equals(key.split("_")[0]) && str2.equals(key.split("_")[1])) {
                if (str3.equals(key.split("_")[2])) {

                } else {
                    return true;
                }
            }
        }
//        if (map.get(key) != null) {
//            return true;
////            String betType = key.split("_")[2];//投注玩法
////            map
//        }
        Log.v("", "key---" + key);
        return false;
    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        String keyTemp = compoundButton.getTag() + "";
        String key = keyTemp.substring(0, 1);
        if (isSelectCurrentMatch(gPosition + "_" + cPosition + "_" + key)) {
            compoundButton.setChecked(false);
            ByAlert.alert("一场比赛只能选择一种类型进行投注");
        } else {
            clearAndBuildData();
        }
    }
}
